<?php

class AnswerController extends ControllerBase
{   
    //定义题目数据结构
    protected $TestArray = array(
        "status"  => "error",
        "title"   => "",
        "no"      => 0,
        "question"=> "",
        "option_1"=> "",
        "option_2"=> "",
        "option_3"=> "",
        "option_4"=> ""
        );

    public function initialize()
    {
        $this->tag->setTitle('答题中心');
        parent::initialize();
    }

    public function indexAction()
    {
        
        $testId = $this->session->get('auth')['testId'];
        $uid = $this->session->get('auth')['uid'];

        //检查是否在答题时间内
        if(!$this->_checkTimeAndJmp($testId, $uid)){
            return;
        }

        //向模板输出变量
        $this->view->username = $this->session->get('auth')['name'];
        $this->view->role = $this->session->get('auth')['role'];
        //初始化用户题库
        $this->view->test = $this->_getTestAction();

        //检查用户是否完成题目
        if($this->_checkIfFinished($testId, $uid))
        {
            $this->forward('answer/finished');
        }

        //向模板输出变量
        $this->view->total = $this->session->get('test')['total'];
        $this->view->finished = $this->session->get('test')['finished'] + 1;
    }

    public function submitAction()
    {
        $uid = $this->session->get('auth')['uid'];
        $testId = $this->session->get('auth')['testId'];
        
        //检查是否在答题时间内
        if(!$this->_checkTimeAndJmp($testId, $uid)){
            return;
        }

        if ($this->request->isPost()) {
            if($this->request->getPost("select")) {
                $num = $this->request->getPost("select");
                if(is_numeric($num)) {
                    $answer = Answers::findFirst(array(
                        "checked = :checked: AND user = :user: AND test = :test:",
                        'bind' => array('user' => $uid, 'test' => $testId, 'checked' => 0),
                        'order' => 'no'
                    ));

                    if($answer->setChoice($num)){
                        $answer->setChecked(1);
                        $answer->save();
                    }

                    //sum the score
                    $this->_sumMark($testId, $uid);
                    $this->_countRadio($testId, $uid);
                    echo "success";
                }
            }
        }
        echo "error";
    }

    public function finishedAction()
    {
        $this->view->username = $this->session->get('auth')['name'];
        $this->view->role = $this->session->get('auth')['role'];

        $testId = $this->session->get('auth')['testId'];
        $uid = $this->session->get('auth')['uid'];

        $result = Result::findFirst(array(
            "user = :user: AND test = :test:",
            'bind' => array('user' => $uid, 'test' => $testId)
        ));
        $total = $result->getMark();
        $this->view->total = $total;

    }

    public function closedAction()
    {
        $this->view->username = $this->session->get('auth')['name'];
        $this->view->role = $this->session->get('auth')['role'];
    }

    public function earlyAction()
    {
        $this->view->username = $this->session->get('auth')['name'];
        $this->view->role = $this->session->get('auth')['role'];
    }

    private function _getTestAction()
    {   
        $testId = $this->session->get('auth')['testId'];
        $uid = $this->session->get('auth')['uid'];

        //check if result had existed
        $test = Result::findFirst(array(
            "user = :user: AND test = :test:",
            'bind' => array('user' => $uid, 'test' => $testId)
        ));

        if($test == false){
            //$this->_createTest($testId, $uid);
            $this->forward('index');
            return;
        }
        
        $test = Answers::findFirst(array(
            "checked = :checked: AND user = :user: AND test = :test:",
            'bind' => array('user' => $uid, 'test' => $testId, 'checked' => 0),
            'order' => 'no'
        ));

        $res = Answers::find(array(
            "user = :user: AND test = :test:",
            'bind' => array('user' => $uid, 'test' => $testId)
        ));

        $total = count($res);

        $res = Answers::find(array(
            "checked = :checked: AND user = :user: AND test = :test:",
            'bind' => array('user' => $uid, 'test' => $testId, 'checked' => 1)
        ));

        $finished = count($res);

        //create result
        if($test != false){
            $this->TestArray['status'] = 'success';
            $this->TestArray['title'] = $test->testDetails->getTitle();
            $this->TestArray['no'] = $test->getNo();
            $this->TestArray['question'] = $test->testDetails->getQuestion();
            $this->TestArray['option_1'] = $test->testDetails->getOption_1();
            $this->TestArray['option_2'] = $test->testDetails->getOption_2();
            $this->TestArray['option_3'] = $test->testDetails->getOption_3();
            $this->TestArray['option_4'] = $test->testDetails->getOption_4();
            //markdown about test
            $this->session->set('test', array(
                'no'       =>  $test->getNo(),
                'finished' =>  $finished,
                'total'    =>  $total
            ));
        }else{
            $this->session->set('test', array(
                'finished' =>  $finished,
                'total'    =>  $total
            ));
        }
        
        return $this->TestArray;
    }   

    //todo
    //不需要了
    private function _createTest($testId, $uid)
    {
        $result = new Result();
        $result->setUser($uid);
        $result->setTest($testId);
        $result->setMark(0);
        $result->setRatio(0);
        $result->setChecked(0);
        if($result->save() != false){
            $tests = TestDetails::find(array(
                "test = :test:",
                'bind' => array('test' => $testId),
                'order' => 'id' 
            ));
            
            if($tests != false){
                $id = 1;

                foreach($tests as $test){
                    
                    $answers = new Answers();
                    $answers->setUser($uid);
                    $answers->setNo($id);
                    $answers->setTest_db($test->getId());
                    $answers->setTest($testId);
                    $answers->setChoice(0);
                    $answers->setChecked(0);
                    $answers->save();
                    $id = $id + 1;
                }
            }
        }
    }

    private function _sumMark($testId, $uid)
    {
        $answers = Answers::find(array(
            "checked = :checked: AND user = :user: AND test = :test:",
            'bind' => array('user' => $uid, 'test' => $testId, 'checked' => 1)
        ));


        $total = 0;
        foreach($answers as $answer){
            if($answer->getChoice() ==  $answer->testDetails->getCorrect_answer()){
                $total = $total + $answer->testDetails->getScore();
            }
        }
        $result = Result::findFirst(array(
            "user = :user: AND test = :test:",
            'bind' => array('user' => $uid, 'test' => $testId)
        ));
        $result->setMark($total);
        $result->save();
    }

    private function _checkIfFinished($testId,$uid)
    {
        $c1 = Answers::count(array(
            "checked = :checked: AND user = :user: AND test = :test:",
            'bind' => array('user' => $uid, 'test' => $testId, 'checked' => 0)
        ));

        $c2 = Answers::count(array(
            "user = :user: AND test = :test:",
            'bind' => array('user' => $uid, 'test' => $testId)
        ));

        //排除没有答完和题目没有创建的情况
        if($c1 > 0 or $c2 == 0){
            return false;
        }else{
            $result = Result::findFirst(array(
                "user = :user: AND test = :test:",
                'bind' => array('user' => $uid, 'test' => $testId)
            ));
            if($result){
                if($result->getChecked() == 0){
                    //标记题目已经完成
                    $result->setChecked(1);
                    $result->save();
                }
            }
            return true;
        }
    }

    private function _countRadio($testId,$uid)
    {
        $answers = Answers::find(array(
            "checked = :checked: AND user = :user: AND test = :test:",
            'bind' => array('user' => $uid, 'test' => $testId, 'checked' => 1)
        ));

        $total = count($answers);
        $count = 0;
        foreach ($answers as $answer) {
            if($answer->getChoice() == $answer->testDetails->getCorrect_answer()){
                $count = $count + 1;
            }
        }

        $result = Result::findFirst(array(
            "user = :user: AND test = :test:",
            'bind' => array('user' => $uid, 'test' => $testId)
        ));
        $result->setRatio(number_format($count * 1.00 / $total, 4));
        $result->save();
    }

    private function _checkTimeAndJmp($testId, $uid)
    {
        $timer = new TimerController();
        $beginTime = $timer->getBeginTime($testId);
        $endTime = $timer->getEndTime($testId);

        if($beginTime == 'error' or $endTime == 'error')
        {
            return false;
        }

        //检查是否没到测试时间
        if($beginTime > 0)
        {
            $this->forward('answer/early');
            return false;
        }

        //检查测试是否结束
        if($endTime < 0)
        {
            //比赛结束后，设置用户题目已完成
            $this->_afterClose($testId, $uid);
            $this->forward('answer/closed');
            return false;
        }
        return true;
    }

    private function _afterClose($testId, $uid)
    {
        $result = Result::findFirst(array(
            "user = :user: AND test = :test:",
            'bind' => array('user' => $uid, 'test' => $testId)
        ));

        $result->setChecked(1);
        $result->save();
    }
}
